package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.mappers.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setIsDefault(0);

        addressBookMapper.save(addressBook);

    }

    @Override
    public R<List<AddressBook>> findAll(Long userId) {
        List<AddressBook> addressBooks = addressBookMapper.findAll(userId);

        return R.success(addressBooks);
    }

    @Override
    public void updateDefault(AddressBook addressBook) {
        addressBookMapper.closeAllDefault(addressBook.getUserId());

        addressBookMapper.updateDefault(addressBook);

    }

    @Override
    public R<AddressBook> findById(Long id) {
        AddressBook addressBook = addressBookMapper.findById(id);
        return R.success(addressBook);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookMapper.update(addressBook);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public AddressBook getDefaultAddress(Long userId) {
        return addressBookMapper.getDefaultAddress(userId);
    }
}
